#include "widget.h"
#include "ui_widget.h"





Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    //this->setVisible(false);

#if 0
    cv::Mat image=cv::imread("aa.jpg",1);
    //namedWindow("jmmmm");
    imshow("jmmm",image);
#endif

    tes001show();




}

Widget::~Widget()
{
    delete ui;
}






std::vector<cv::Point> findBiggestContour(cv::Mat binary_image)
{
    std::vector<std::vector<cv::Point>> contours;
    std::vector<cv::Vec4i> hierarchy;

    int largest_area = 0;
    int largest_contour_index = 0;

    cv::findContours(binary_image, contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE);

    for (int i = 0; i < contours.size(); i++) // iterate through each contour.
    {
        double a = contourArea(contours[i], false);  //  Find the area of contour
        if (a > largest_area){
            largest_area = a;
            largest_contour_index = i;                //Store the index of largest contour
        }
    }

    return contours[largest_contour_index];
}


int Widget::tes001show()
{
    //std::string in_name = "./bb.mp4";
    VideoCapture cap("D:\\00work\\qtproject001\\openCV01\\OpenCV_applications\\openCV_01\\bb.mp4");

    while(1)
    {
        Mat frame;
        cap >> frame;
        if(frame.empty())
        {
            qDebug()<<"finished, break";
            break;
        }

        tes001(frame);

        sleepMsec(10);
    }
    return 1;
}

int Widget::tes001(cv::Mat src)
{



    //cv::Mat src = cv::imread("aa.jpg", 1);



        cv::Mat result = src.clone();
        cv::Mat gray;
        cv::cvtColor(src, gray, CV_BGR2GRAY);
        cv::Mat binary;
        cv::threshold(gray, binary, 100, 255, cv::THRESH_BINARY);

        std::vector< std::vector< cv::Point> > contours;
        std::vector< cv::Point>  biggest_contour;
        std::vector< std::vector< cv::Point> > temp_contours;
        cv::findContours(
            binary,
            contours,
            cv::noArray(),
            cv::RETR_LIST,
            cv::CHAIN_APPROX_SIMPLE
            );
        biggest_contour = findBiggestContour(binary);
        temp_contours.push_back(biggest_contour);

        cv::drawContours(result, contours, -1, cv::Scalar(0, 255, 0));
        cv::drawContours(result, temp_contours, 0, cv::Scalar(0, 0, 255));



        cv::imshow("src", src);
        cv::imshow("gray", gray);
        cv::imshow("binary", binary);
        cv::imshow("result", result);
        //cv::waitKey(0);

        return 0;


}


#include<QTimer>

void  Widget:: sleepMsec(int msec)
{
    QEventLoop loop;		//定义一个新的事件循环
    QTimer::singleShot(msec, &loop, SLOT(quit()));//创建单次定时器，槽函数为事件循环的退出函数
    loop.exec();			//事件循环开始执行，程序会卡在这里，直到定时时间到，本循环被退出
}


